package com.wisdytech.ccdserver.common.thread;

import lombok.extern.log4j.Log4j2;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.RejectedExecutionHandler;

/**
 * @description 线程池配置类
 */
@Configuration
@Slf4j
public class OurPoolExecutor {

    @Autowired
    private PoolExecutorConfig threadPoolExecutorConfig;

    @Bean
    public ThreadPoolTaskExecutor threadPoolTaskExecutor() {
        String threadNamePrefix = threadPoolExecutorConfig.getThreadNamePrefix();
        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        try {
            log.info("开始初始化线程池 -->threadPoolTaskExecutor");
            taskExecutor.setThreadNamePrefix(threadNamePrefix);
            taskExecutor.setCorePoolSize(threadPoolExecutorConfig.getCorePoolSize());
            taskExecutor.setMaxPoolSize(threadPoolExecutorConfig.getMaxPoolSize());
            taskExecutor.setQueueCapacity(threadPoolExecutorConfig.getQueueCapacity());
            //通过反射获取RejectedExecutionHandlerClass 的类模板
            Class<?> rejectedExecutionHandlerClass = Class.forName(threadPoolExecutorConfig.getRejectedExecutionHandler());
            //获取RejectedExecutionHandlerClass类的实例
            RejectedExecutionHandler rejectedExecutionHandler = (RejectedExecutionHandler) rejectedExecutionHandlerClass.newInstance();
            taskExecutor.setRejectedExecutionHandler(rejectedExecutionHandler);
            taskExecutor.setKeepAliveSeconds(threadPoolExecutorConfig.getKeepAliveSeconds());
            //进行加载
            taskExecutor.initialize();
            log.info("初始化线程池完成:{}核心线程为{}-->", threadNamePrefix, taskExecutor.getCorePoolSize());
            return taskExecutor;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("初始化线程池失败:{}失败原因为:{}", threadNamePrefix, e.getMessage());
            return null;
        }
    }

}

